﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UIT.Controls.Template;
using UIT.Converters;
using System.ComponentModel;

namespace UIT.Controls.Data
{
    public class ItemsControl : Control, IDataConsumer
    {

        public ItemsControl()
        {
            Wrappers = new DisposableObservableCollection<ItemsControl, ItemWrapper>(this);
        }

        public IDisposableObservableCollection<ItemsControl, ItemWrapper> Wrappers { get; private set; }


        public DataTemplate ItemTemplate { get; set; }

        private ItemsPanelTemplate itemsPanel;

        public ItemsPanelTemplate ItemsPanel
        {
            get { return itemsPanel; }
            set
            {
                itemsPanel = value;
                OnPropertyChanged("ItemsPanel");
            }
        }

        #region IDataConsumer Members

        private IDataProvider dataSource;

        [System.ComponentModel.TypeConverter(typeof(DataProviderConverter))]
        public IDataProvider DataSource
        {
            get { return dataSource; }
            set
            {
                if (dataSource != value)
                {
                    dataSource = value;
                    OnPropertyChanged("DataSource");
                }
            }
        }

        #endregion

        public override bool IsContainer
        {
            get { return false; }
        }

        public override ControlType Type
        {
            get { return ControlType.Master; }
        }
        public class ItemWrapper : IContainable<ItemsControl>, INotifyPropertyChanged, IDisposable
        {
            public ItemWrapper(ItemsControl parent)
            {
                this.parent = parent;
            }

            public object Item { get; internal set; }
            public DataTemplateInstance View { get; internal set; }

            private ItemsControl parent;

            public ItemsControl Parent
            {
                get { return parent; }
                set
                {
                    parent = value;
                    OnPropertyChanged("Parent");
                }
            }

            private void OnPropertyChanged(string propertyName)
            {
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }

            public event PropertyChangedEventHandler PropertyChanged;

            public void Dispose()
            {
                View = null;
                Item = null;
            }
        }

        public void Wrap(DataTemplateInstance child, object item)
        {
            Wrappers.Add(new ItemWrapper(this) { Item = item, View = child });
        }
    }
}
